import { useState } from 'react';
import { chatStream } from '@/api/message';
import { ChatResult } from './useChat';

export const useStreamChat = () => {
  const [streaming, setStreaming] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const streamChat = async (
    message: string, 
    conversationId: string,
    onUpdate: (result: ChatResult) => void,
    agentId?: number
  ) => {
    setStreaming(true);
    setError(null);
    
    try {
      const stream = await chatStream({
        content: message,
        conversationId,
        ...(agentId && { agentId })
      });
      const result = {
        content:'',
        reasonContent:''
      }
     
      for await (const chunk of stream as any) {
        if (chunk.choices?.[0]?.delta?.reasoning_content || chunk.reasoningContent) {
          
          result.reasonContent += chunk.choices?.[0]?.delta?.reasoning_content || chunk.reasoningContent;
        } else {
          // if (isThink && !thinkFinish) {
          //   thinkFinish = true;
          //   content += "</think>\n\n";
          // }
          result.content += chunk.choices?.[0]?.delta?.content || chunk.content || '';
        }
        
        // 实时更新内容
        onUpdate(result);
      }

      return result;
    } catch (err) {
      setError(err as Error);
      throw err;
    } finally {
      setStreaming(false);
    }
  };

  return { streamChat, streaming, error };
}; 